package middol.notice.impl


import grails.plugins.mail.MailService
import grails.util.Holders
import middol.notice.EmailMessage
import middol.notice.IMessage
import middol.notice.INoticeHandler
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
* @Description:    邮件通知
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/10/21 10:21
* @Version:        1.0
*/
@Component
class EmailNoticeHandler implements INoticeHandler {
    static final String name = "Email"
    @Autowired
    MailService mailService = Holders.grailsApplication.mainContext.getBean(MailService.class)

    @Override
    void handleSend(IMessage message) {
        EmailMessage emailMessage = message as EmailMessage
        mailService.sendMail {
            to emailMessage?.tos
            from "${Holders.grailsApplication.config.grails.mail.default.from}"
            subject emailMessage?.subject

            if(emailMessage?.text){
                text emailMessage?.text
            }
            if(emailMessage?.html){
                html view: emailMessage?.html?.view, model: emailMessage?.html?.model
            }
            if(emailMessage?.ccs){
                cc emailMessage?.ccs
            }
            if(emailMessage?.bccs){
                bcc emailMessage?.bccs
            }
            if(emailMessage?.attachBytes && emailMessage?.attachBytes?.size() > 0){
                multipart true
                emailMessage?.attachBytes.each {
                    attachBytes(it.fileName, "application/octet-stream;chartset=UTF-8", it.attachBytes)
                }
            }
        }
    }


}
